/* 页面跳转 */
function jumpLogin() {
    location.href = '/html/login.html'
  }
  
  function jumpRegister() {
    location.href = '/html/register.html'
  }
  
  /* 验证 */
  var formEle = document.querySelector('form')
  var usernameInput = document.querySelector('input[name="username"]')
  var passwordInput = document.querySelector('input[name="password"]')
  //用户名提示信息元素
  var userMsgEle = document.querySelector('.username-text')
  //密码提示信息元素
  var pswMsgEle = document.querySelector('.password-text')
  
  /* 焦点 */
  function usernameValidate() {
    usernameInput.addEventListener('blur', function () {
      //非空验证-用户密码不能为空
      if (checkUserNameIsNull() == false) {
        return
      }
    })
  }
  
  function passwordValidate() {
    passwordInput.addEventListener('blur', function () {
      if (checkPasswordIsNull() == false) {
        return
      }
      if (checkPassword() == false) {
        return
      }
    })
  }
  
  /*非空验证 true通过false不通过*/
  function checkUserNameIsNull() {
    var userName = usernameInput.value
    //用户名检查
    if (userName == '') {
      userMsgEle.innerHTML = '用户名不能为空!'
      return false
    } else {
      userMsgEle.innerHTML = '' //清除用户名提示信息
      return true
    }
  }
  /**
   * 密码非空验证
   */
  function checkPasswordIsNull() {
    var passWord = passwordInput.value
    //密码检查
    if (passWord == '') {
      pswMsgEle.innerHTML = '密码不能为空!'
      return false
    } else {
      pswMsgEle.innerHTML = '' //清除密码提示信息
      return true
    }
  }
  /*
    密码强度验证
       1. 必须是大写字母开头  [A-Z]
       2. 密码包含字母和数字
       3. 至少8位
  */
  function checkPassword() {
    const password = passwordInput.value //密码字符串 
    const reg = /^[A-Z][0-9a-zA-Z]{7,}/ //密码强度正则表达式
    if (reg.test(password)) {
      pswMsgEle.innerHTML = '' //清除提示信息
      return true
    } else {
      pswMsgEle.innerHTML = '请输入大写字母开头，至少8位字母数字组合!'
      return false
    }
  }
  /* 注册 */
  function getPost() {
    formEle.addEventListener('submit', e => {
      let username = usernameInput.value
      let password = passwordInput.value
      e = e || window.event //事件对象
      e.preventDefault() //阻止事件默认行为
      //1.1 非空验证-用户密码不能为空
      if (checkUserNameIsNull() == false) {
        return
      }
      if (checkPasswordIsNull() == false) {
        return
      }
      //1.2密码强度验证
      if (checkPassword() == false) {
        return
      }
      axios({
        method: 'post',
        url: 'http://api.yuguoxy.com/api/member/add',
        data: {
          username,
          password
        }
      }).then(response => {
        let data = response.data
        if (data.resultCode == 1) {
          alert('注册成功')
          location.href = '/html/login.html'
        } else {
          alert('用户名已存在!请重新输入!')
        }
      })
    })
  }
  
  usernameValidate()
  passwordValidate()
  getPost()